package NIO;

import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioTimerServer {

    public static void main(String[] args) {
        int port = 8088;
        MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port);
        new Thread(timeServer , "Nio-timeServer").start();
    }

    static class MultiplexerTimeServer implements Runnable {

        private Selector selector;

        private ServerSocketChannel serverSocketChannel;

        private volatile boolean stop;

        public MultiplexerTimeServer(int port) {
            try {
                selector = Selector.open();
                serverSocketChannel = ServerSocketChannel.open();
                serverSocketChannel.configureBlocking(false);
                serverSocketChannel.socket().bind(new InetSocketAddress(port) , 1024);
                serverSocketChannel.register(selector , SelectionKey.OP_ACCEPT);
                System.out.println("The time server is start in port :"+port);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        public void stop() {
            stop = true;
        }

        @Override
        public void run() {
            while (!stop) {
                try {
                    //Selects a set of keys whose corresponding channels are ready for I/Ooperations.
                    selector.select(1000);
                    Set<SelectionKey> selectionKeys =  selector.selectedKeys();
                    Iterator<SelectionKey> iterable = selectionKeys.iterator();
                    SelectionKey key = null;
                    while (iterable.hasNext()) {
                        key = iterable.next();
                        iterable.remove();
                        try {
                            handleInput(key);
                        }catch (Exception e) {
                            if (key != null) {
                                key.cancel();
                                if (key.channel() != null) {
                                    key.channel().close();
                                }
                            }
                        }
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //关闭多路复用器，注册在上面的Channel和Pipe都会关闭
            if (selector != null) {
                try {
                    selector.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void handleInput(SelectionKey key) throws IOException {
            if (key.isValid()) {
                if (key.isAcceptable()) {
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector , SelectionKey.OP_READ);
                }

                if (key.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int readBytes = socketChannel.read(byteBuffer);
                    if (readBytes > 0) {
                        byteBuffer.flip();
                        byte[] bytes = new byte[byteBuffer.remaining()];
                        byteBuffer.get(bytes);
                        String body = new String(bytes , "utf-8");
                        System.out.println("The time server receive order : "+body);
                        String currTime = String.valueOf(System.currentTimeMillis());
                        doWrite(socketChannel , currTime);
                    }else if(readBytes < 0) {
                        key.cancel();
                        socketChannel.close();
                    }else {

                    }
                }
            }
        }

        private void doWrite(SocketChannel socketChannel, String currTime) throws IOException {
            if (StringUtils.isNotBlank(currTime)) {
                byte[] bytes = currTime.getBytes();
                ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
                writeBuffer.put(bytes);
                writeBuffer.flip();
                socketChannel.write(writeBuffer);
            }
        }
    }
}
